import Vue from 'vue'
import debugCfg from 'share/debugCfg.js'

var hostname = window.location.hostname
if (debugCfg.debugOn) {
  hostname = debugCfg.ctServerIp
}

export function makeUri(processName, devId, entry) {
  return `/devs/${devId}/${processName}/${entry}`
}

function makeApiUri(processName, devId, entry) {
  return `/api/${processName}/${entry}`
}

export function setHostname(str) {
  hostname = str
}

export function getUrlPrefix(scheme) {
  var useScheme = scheme || 'http'
  if (hostname !== '') {
    return `${useScheme}://${hostname}:9080`
  } else if (debugCfg.debugOn) {
    return `${useScheme}://${debugCfg.ctServerIp}:9080`
  } else {
    return ''
  }
}

export function newWebsocket(uri) {
  return new WebSocket(getUrlPrefix('ws') + uri, ['chat'])
}

export function http(uri, method, data, {timeout = 10000, headers = {}, upload = {}} = {}) {
  var options = {
    url: getUrlPrefix() + encodeURI(uri),
    method: method,
    timeout: timeout, 
    data: data,
    headers: headers,
    upload: upload
  }

  if ((hostname !== '')
    || (debugCfg.debugOn)) {
    options.xhr = {}
    options.xhr.withCredentials = true
  }
  return Vue.http(options)
}

import {ProcessApi, StorageApi, RestApi} from 'libs/api.js'

export var systemApi = new ProcessApi(http, 'sys', 0, makeUri)
export var streamSrcApi = new ProcessApi(http, 'streamsrc', 0, makeUri)
export var multimediaApi = new ProcessApi(http, 'multimedia', 0, makeUri)
export var devmngApi = new ProcessApi(http, 'devmng', 0, makeUri)
export var mediaPhyApi = new ProcessApi(http, 'mediaPhy', -1, makeUri)
export var mediaApi = new ProcessApi(http, 'media', 0, makeUri)
export var transferApi = new ProcessApi(http, 'transfer', -1, makeUri)

export var clusterApi = new ProcessApi(http, 'cluster', 0, makeApiUri)
export var commonApi = new ProcessApi(http, 'common', 0, makeApiUri)

function runShell(shName) {
  let paramlist = {
    shName: shName
  }

  return commonApi.sendCmd('runShell', paramlist)
}

export var shortcutApi = {
  runShell: runShell,
  reboot () {
    runShell('restart.sh')
  }
}

export var storageApi = new StorageApi(http)

export var webAppApi = new RestApi(http, 'webapp')
export var scriptApi = new RestApi(http, 'script')

